package com.wkk.controller;

import com.wkk.entity.*;
import com.wkk.service.AdminService;
import com.wkk.service.CourseService;
import com.wkk.service.UserService;
import com.wkk.util.GeneralCalculation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private AdminService adminService;

    //实现页面跳转
    @RequestMapping("/{path}")
    public String toPath(@PathVariable("path")String path,HttpSession session){
        User user  =  (User)session.getAttribute("nowUser");
        if(user!=null){
            if(user.getLevel().equals("admin")&&path.equals("login-admin")){
                return "index-admin";
            }
            if(user.getLevel().equals("user")&&path.equals("login")){
                return "index-member";
            }
            if(user.getLevel().equals("member")&&path.equals("login")){
                return "index-member";
            }
            if(user.getLevel().equals("coach")&&path.equals("login-coach")){
                return "index-coach";
            }
        }
        return path;
    }


    //实现文件上传
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    //解决挂起的重复调用接口
    private static  List<UploadInfo> uploadInfoList = new ArrayList<>();

    @ResponseBody
    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }

    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request){

        Integer selectId = Integer.parseInt(request.getParameter("selectId"));
        UploadInfo up =  new UploadInfo(selectId,file.getOriginalFilename());
        if(uploadInfoList.size()>0){
            for(UploadInfo uploadInfo:uploadInfoList){
                if(up.getId()==uploadInfo.getId()&&up.getFileName().equals(uploadInfo.getFileName())){
                    return "上传失败";
                }
            }
        }
        uploadInfoList.add(up);
    /*    List<UploadInfo> uploadInfos = new ArrayList<>();
        for(UploadInfo uploadInfo:uploadInfos){
            if(uploadInfo.getFileName().equals(file.getOriginalFilename())&&uploadInfo.getId()==selectId){
                System.out.println(uploadInfo);
                return "上传失败";
            }
        }
        uploadInfos.add(new UploadInfo(selectId,file.getOriginalFilename()));*/
        if(file.isEmpty()){
            return "文件上传失败";
        }

        //用于产生随机生成数,防止上传的图片出现重明问题
        // String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
      String str = (new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date());
        String fileName = file.getOriginalFilename();
      String[] s=fileName.split("\\.");
      str=str+"."+s[1];
        String filepath = "D:\\IdeaItem\\fitnessManagement\\fitness\\src\\main\\resources\\static\\img\\";
        File dest = new File(filepath+str);

        try{
            file.transferTo(dest);
            logger.info("上传成功");
           return str;//将上传成功的图片名字返回到前端页面,用于实现数据库读入
        }catch(IOException e){
            logger.info("上传失败");
            e.printStackTrace();
        }
        return "上传失败";
    }


    //在用户登录时，判断是否需要给予提醒（课程预约）
    @ResponseBody
    @RequestMapping("userLogin")
    public String userLogin(User user,HttpSession session){
        session.removeAttribute("nowUser");//解决主管端和用户端一个账号同时登陆问题
        if(user.getUsername().length()==11){
            user.setMobile(user.getUsername());
        }
        User nowUser = userService.userLogin(user);
        if(nowUser == null){
            return "0";
        }else{
            Map<User, HttpSession> userMap = (Map<User, HttpSession>)
                    session.getServletContext().getAttribute("userMap");
            // 判断用户是否已经在map集合中'
            if(userMap.containsKey(nowUser)){
                // 说用map中有这个用户.
                HttpSession userSession = userMap.get(nowUser);
                // 将这个session销毁.
                userSession.invalidate();
            }
            //该步实现对会员到期的用户进行级别修改
            GeneralCalculation generalCalculation =new GeneralCalculation();
            if(nowUser.getEndMember()!=null&&!nowUser.getEndMember().equals("")&&nowUser.getLevel().equals("member")) {
                if (generalCalculation.judgeTime(nowUser.getEndMember()) > 0) {
                    userService.updateToUser(nowUser.getUid());
                    nowUser.setLevel("user");
                }
            }
            // 使用监听器:HttpSessionBandingListener作用在JavaBean上的监听器.
            //用于获取当前的用户信息
            session.setAttribute("nowUser", nowUser);

            if(nowUser.getLevel().equals("coach")){
                return "3";
            }

            if(nowUser.getLevel().equals("admin")){
                return "2";
            }
            //实现用户登录即签到
            SignIn sign = new SignIn();
            sign.setUid(nowUser.getUid());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            sign.setDate(simpleDateFormat.format(new Date()));
            adminService.userSignIn(sign);

            //获取所有的课程信息
            session.setAttribute("allCourse",courseService.selectListByMoldOrTeacher(null));
            //用于加载用户主页的公共课程
            session.setAttribute("commentCourses",courseService.selectListByMoldOrTeacher("公共课"));
        }
        return "1";
    }


    @ResponseBody
    @RequestMapping("userRegister")
    public String userRegister(User user){
        System.out.println(user);
        return userService.userRegister(user);
    }


    @ResponseBody
    @RequestMapping("quit")
    public String quit(HttpSession session){
        session.invalidate();
        return "index";
    }


    @ResponseBody
    @RequestMapping("userInfoUpdate")
    public String userInfoUpdate(User user){
        return userService.userInfoUpdate(user);
    }

    @ResponseBody
    @RequestMapping("userChangePassword")
    public String userChangePassword(@RequestParam("mobile")String mobile,HttpSession session){
        userService.userChangePassword(mobile);
        session.invalidate();
        return "1";
    }

    @ResponseBody
    @RequestMapping("userChangePasswordByUid")
    public String userChangePasswordByUid(User user,HttpSession session){
        userService.userChangePassword(user);
        session.invalidate();
        return "1";
    }

    //条件查询(current,condition/pageMsg)---真分页
    @ResponseBody
    @RequestMapping("selectPageByCondition")
    public PageBean<User> selectPageByCondition(@RequestParam(value = "current",defaultValue = "1",required = false)Integer current,
                                 @RequestParam(required = false,value = "condition")String condition,
                                                HttpSession session){
        //若是条件查询翻页，则确保上次的session还存在
        String  lastCondition = (String)session.getAttribute("condition");
        //什么时候采用传入的condition进行查询：
        // 1.默认无条件,且之前未进行过条件查询，故：condition==null&&lastCondition==null
        // 2.新的条件传入,不管先前有什么条件都将覆盖，故：condition!=null
        // 综上所述则要么有新的条件传入，要么是无条件查询，故：condition!=null||lastCondition==null
        if(condition!=null||lastCondition==null){//若是第一次提交，则保存条件入session用于翻页时条件不丢失
            session.setAttribute("condition",condition);
            return userService.selectPageByCondition(current,condition);
        }
        //用于获取第二次以上的分页查询信息获取
        return userService.selectPageByCondition(current,lastCondition);
    }

    //精确模糊查询(User/pageMsg)----真分页
    @ResponseBody
    @RequestMapping("queryPageByUserInfo")
    public PageBean<User> queryPageByUserInfo(User queryUser){
        return userService.queryPageByUserInfo(queryUser);
    }

    //修改用户信息(User current/User)----真分页
    @ResponseBody
    @RequestMapping("updateUserInfo")
    public PageBean<User> updateUserInfo(User user,@RequestParam(value = "current",defaultValue = "1",required = false)Integer current,HttpSession session){
        //获取更新接口前传递的条件，防止出现数据异常
        String  lastCondition = (String)session.getAttribute("condition");
        String  infoUpdate=  userService.userInfoUpdate(user);//通过uid更新用户传递的新信息
        if(infoUpdate.equals("成功")){
        return userService.selectPageByCondition(current,lastCondition);//将获取过后的页面信息重新传递回去
        }
        PageBean<User> pageBean = new PageBean<>();
        pageBean.setCurrent(0);
        return pageBean;//返回一个空页
    }

    //删除用户信息(uid,current/pageMsg)----真分页
    @ResponseBody
    @RequestMapping("deleteUserInfo")
    public PageBean<User> deleteUserInfo(@RequestParam("uid")Integer uid,@RequestParam(value = "current",defaultValue = "1",required = false)Integer current,HttpSession session){
        //获取更新接口前传递的条件，防止出现数据异常
        String  lastCondition = (String)session.getAttribute("condition");
        userService.deleteUserByUid(uid);//通过uid更新用户传递的新信息
        return userService.selectPageByCondition(current,lastCondition);//将获取过后的页面信息重新传递回去
    }

    //获取单个用户信息(uid/User)
    @ResponseBody
    @RequestMapping("selectOne")
    public User selectOne(@RequestParam("uid")Integer uid){
        return userService.selectOne(uid);
    }

    //实现用户升级成大会员
    @ResponseBody
    @RequestMapping("upToMember")
    public User upToMember(@RequestParam("uid")Integer uid,@RequestParam("cid")Integer cid,@RequestParam("myself")String myself,HttpSession session){
        userService.upToMember(uid,cid,myself);
        User user = userService.selectOne(uid);
        session.setAttribute("nowUser",user);
        return user;
    }

    @ResponseBody
    @RequestMapping("list")
    public List<User> userList(){
        return userService.selectList();
    }

    @ResponseBody
    @RequestMapping("addMember")
    public String addMember(User user){
        return userService.userRegister(user);
    }

    @ResponseBody
    @RequestMapping("updateUserByMember")
    public User updateUserByMember(User user,HttpSession session){
        User nowUser = userService.updateByMember(user);
        session.setAttribute("nowUser",nowUser);
        return nowUser;
    }

    @ResponseBody
    @RequestMapping("getMemberByCid")
    public List<User> getMemberByCid(@RequestParam("cid")Integer cid){
        return userService.selectListByCid(cid);
    }
}
